<?php

/**
 * This is the model class for table "product".
 *
 * The followings are the available columns in table 'product':
 * @property integer $product_id
 * @property string $name
 * @property string $description
 * @property integer $category_id
 * @property integer $order
 * @property string $image
 * @property string $price
 * @property integer $status
 * @property integer $product_type_id
 * @property string $special
 * @property string $special_start
 * @property string $special_end
 */
class Product extends CActiveRecord {

    public $valueProperties = array();
    public $categories = array();

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return 'product';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('name,quantity,price,code', 'required', 'message' => 'trường này không được bỏ trống'),
            array('code', 'unique', 'message' => 'code sản phẩm phải là duy nhất'),
            array('quantity,product_id, category_id, order, status, product_type_id,special', 'numerical', 'integerOnly' => true),
            array('name, image', 'length', 'max' => 255),
            array('price', 'length', 'max' => 10),
            array('special', 'length', 'max' => 11),
            array('description, special_start, special_end,valueProperties,seo_title,seo_keywork,seo_description,sortprice,total_rating,count_rating,avg_rating,categories', 'safe'),
            array('image', 'file', 'types' => 'jpg, gif, png', 'allowEmpty' => true, 'message' => 'bạn chỉ được upload file hình png,jpg hoặc gif'),
            // The following rule is used by search().
            // @todo Please remove those attributes that should not be searched.
            array('product_id, name, description, category_id, order, image, price, status, product_type_id, special, special_start, special_end', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'category' => array(self::BELONGS_TO, 'Category', 'category_id'),
            'values' => array(self::HAS_MANY, 'ProductProperty', 'product_id'),
            'images' => array(self::HAS_MANY, 'Image', 'product_id'),
            'stars' => array(self::HAS_MANY, 'Star', 'object_id'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'product_id' => 'Product',
            'name' => 'Tên sản phẩm',
            'description' => 'Mô tả',
            'category_id' => 'Danh mục chính',
            'order' => 'Thứ tự',
            'image' => 'Hình ảnh',
            'price' => 'Giá',
            'status' => 'Status',
            'product_type_id' => 'Loại sản phẩm',
            'special' => 'Giá đặc biệt',
            'special_start' => 'Ngày bắt đầu',
            'special_end' => 'Ngày kết thúc',
            'quantity' => 'Số lượng',
            'code' => 'Mã sản phẩm'
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     *
     * Typical usecase:
     * - Initialize the model fields with values from filter form.
     * - Execute this method to get CActiveDataProvider instance which will filter
     * models according to data in model fields.
     * - Pass data provider to CGridView, CListView or any similar widget.
     *
     * @return CActiveDataProvider the data provider that can return the models
     * based on the search/filter conditions.
     */
    public function search() {
        // @todo Please modify the following code to remove attributes that should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('product_id', $this->product_id);
        $criteria->compare('name', $this->name, true);
        $criteria->compare('description', $this->description, true);
        $criteria->compare('category_id', $this->category_id);
        $criteria->compare('order', $this->order);
        $criteria->compare('image', $this->image, true);
        $criteria->compare('price', $this->price, true);
        $criteria->compare('status', $this->status);
        $criteria->compare('product_type_id', $this->product_type_id);
        $criteria->compare('special', $this->special, true);
        $criteria->compare('special_start', $this->special_start, true);
        $criteria->compare('special_end', $this->special_end, true);

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }

    /**
     * Returns the static model of the specified AR class.
     * Please note that you should have this exact method in all your CActiveRecord descendants!
     * @param string $className active record class name.
     * @return Product the static model class
     */
    public static function model($className=__CLASS__) {
        return parent::model($className);
    }

    /**
     * 
     */
    public function afterFind() {
        parent::afterFind();
        foreach ($this->values as $value) {
            $this->valueProperties[$value->property_id][] = $value->property_value_id;
        }
    }

    /**
     * get image of category
     */
    public function getImage() {
        $default = "default.gif";

        if ($this->product_id != null && file_exists(PATH_IMAGE_PRODUCT . $this->image) && strlen($this->image) > 0) {
            return $this->image;
        } else {
            if ($this->product_id != null) {
                return $default;
            }
        }
        return false;
    }
    
    /**
     * 
     */
    public function getLargeImage($width = 930,$height = 704){
        $default = "default.gif";
        if(strlen($this->image) > 0 && file_exists(PATH_IMAGE_PRODUCT . $this->image)){
            $file_name = "large_".$this->image;
            if(!file_exists(PATH_IMAGE_PRODUCT . $file_name)){
                /*$magicianObj = new imageLib(PATH_IMAGE_PRODUCT . $this->image);
                $magicianObj -> resizeImage($width, 704);
                $magicianObj -> saveImage(PATH_IMAGE_PRODUCT . $file_name);*/
            }
            return $file_name;
        }
        return $default;
        
    }

    /**
     * 
     */
    public static function homeProduct($limit) {
        $criteria = new CDbCriteria();
        $criteria->addCondition('`status` = 1 and special != 0');
        $criteria->order = 'special ASC';
        $criteria->limit = $limit;
        return self::model()->findAll($criteria);
    }

    /**
     * get old price
     */
    public function getOldPrice() {
        $special = $this->getSpecialPrice();
        if ($special > 0) {
            return $this->price;
        }
        return 0;
    }

    /**
     *  get price now
     */
    public function getPrice() {
        $special = $this->getSpecialPrice();
        if ($special > 0) {
            return $special;
        }
        return $this->price;
    }

    /**
     * get price special
     */
    public function getSpecialPrice() {
        $start = strtotime($this->special_start);
        $end = strtotime($this->special_end);
        $now = time();
        if ($this->special > 0) {
            return $this->special;
        }
        return 0;
    }

    /**
     * 
     */
    public function getSale() {
        $special = $this->getSpecialPrice();
        if ($special > 0) {
            return 100 - round(($special / $this->price) * 100);
        }
        return false;
    }

    /**
     * 
     */
    public function getRating() {
        return $this->total_rating / $this->count_rating;
    }

    /**
     * 
     */
    public static function getSort($request) {
        $arraySort = array('ASC', 'DESC');
        $arrayField = array('created', 'buy', 'special', 'sortprice');
        $sort = "created DESC";

        if (isset($request['sort']) && preg_match('/(.)+_(.)+-/', $request['sort'])) {
            $sortData = str_replace("_", " ", trim($request['sort'], '-'));
            $data = explode(" ", $sortData);
            if (count($data) == 2 && in_array($data[0], $arrayField) && in_array($data[1], $arraySort)) {
                $sort = $sortData;
            }
        }
        return $sort;
    }

    /**
     * 
     */
    public static function buyProduct($limit) {
        $criteria = new CDbCriteria();
        $criteria->addCondition('`status` = 1');
        $criteria->order = 'buy DESC';
        $criteria->limit = $limit;
        return self::model()->findAll($criteria);
    }

    /**
     * 
     */
    public function listProductSameCategory($limit = 8) {
        return self::model()->findAll('category_id = ' . $this->category_id.' and status = 1', array('order' => 'price ASC', 'limit' => $limit));
    }

    /**
     * 
     */
    public static function getViewdProducts() {
        $return = array();
        if (Yii::app()->request->cookies['viewedProducts'] != null) {
            $viewedProducts = Yii::app()->request->cookies['viewedProducts']->value;
            $arrayProduct = explode("_", trim($viewedProducts, '_'));
            if (count($arrayProduct) > 0) {
                $criteria = new CDbCriteria();
                $criteria->addCondition('`status` = 1');
                $criteria->addInCondition("product_id", $arrayProduct);
                $return = Product::model()->findAll($criteria);
            }
        }
        return $return;
    }

    /**
     * 
     */
    public function getProperties() {
        $id = $this->product_id;
        $return = array();
        $sql = "SELECT * from product_property,property WHERE property.property_id = product_property.property_id AND product_property.product_id = :product_id GROUP BY product_property.property_id";
        $command = $this->dbConnection->createCommand($sql);
        $command->bindParam(":product_id", $id);
        $dataReader = $command->query();
        foreach ($dataReader as $item) {
            $sql = "SELECT * from product_property,property_value WHERE property_value.property_value_id = product_property.property_value_id AND product_property.product_id = :product_id AND property_value.property_id = :property_id";
            $command = $this->dbConnection->createCommand($sql);
            $command->bindParam(":product_id", $id);
            $command->bindParam(":property_id", $item['property_id']);
            $dataValues = $command->query();
            $propertyValues = array();
            foreach ($dataValues as $value) {
                $propertyValues[] = array(
                    'id' => $value['property_value_id'],
                    'name' => $value['name']
                );
            }
            $return[] = array(
                'property' => array(
                    'id' => $item['property_id'],
                    'name' => $item['name']
                ),
                'propertyValue' => $propertyValues
            );
        }
        return $return;
    }
    
    /**
     * 
     */
    public function getUrl(){
       return  Yii::app()->createUrl('product/index',array('title' => getTitleUrl($this->name),'id' => $this->product_id));
    }
    
    /**
     * 
     */
    public function registerMeta(){
       $keyword = $this->seo_keywork != null?$this->seo_keywork:$this->name;
       $description = $this->seo_description != null?$this->seo_description:$this->name;
       Yii::app()->clientScript->registerMetaTag($keyword,'keywords');
       Yii::app()->clientScript->registerMetaTag($description,'description');
    }
    
    /**
     * 
     */
    public function getSeoTitle(){
        if($this->seo_title == null){
            return $this->name;
        }
        return $this->seo_title;
    }
    
    /**
     * 
     */
    public function countStar($number = 5){
        return Star::model()->count('object_id = '.$this->product_id." and star = ".$number);
    }
    
    /**
     * 
     */
    public function getAllCategoryId(){
        $results = CategoryProduct::model()->findAll('product_id = ?', array($this->product_id));
        foreach($results as $result){
            $this->categories[] = $result->category_id;
        }
    }
    
    

}
